package com.luo.gmall.cart.interceptor;

import com.luo.gmall.cart.config.JwtProperties;
import com.luo.gmall.cart.entity.UserInfo;
import com.luo.gmall.common.utils.CookieUtils;
import com.luo.gmall.common.utils.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;

/**
 * @author Zoro
 * @date 2021年11月22
 * 拦截器获取登录信息
 */
@Component
@EnableConfigurationProperties(JwtProperties.class)
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    private static final ThreadLocal<UserInfo> USER_INFO = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从request中获取userId
        String token = CookieUtils.getCookieValue(request, jwtProperties.getCookieName());
        String userKey = CookieUtils.getCookieValue(request, jwtProperties.getUserKey());
        if (StringUtils.isBlank(userKey)) {
            // 没有获取到userKey就生成userKey，将生成的userKey设置到cookies中
            userKey = UUID.randomUUID().toString();
            CookieUtils.setCookie(request, response, jwtProperties.getUserKey(), userKey, jwtProperties.getExpire());
        }
        UserInfo userInfo = new UserInfo(null, userKey);

        if (!StringUtils.isBlank(token)) {
            // 解析token后去userId
            Map<String, Object> map = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            // 将userId设置到登录信息对象
            userInfo.setUserId(Long.valueOf(map.get("userId").toString()));
        }
        // 将登录信息放到线程局部变量对象中
        USER_INFO.set(userInfo);
        System.out.println("handler方法执行前。。。。。");
        return true;
    }

    public UserInfo getUserInfo() {
        // 从ThreadLocal中获取userInfo
        return USER_INFO.get();
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("handler方法执行后，页面渲染前。。。。。。");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在页面渲染前将ThreadLocal中用完的数据清除（请求结束，线程没有结束）
        USER_INFO.remove();
        System.out.println("页面渲染后。。。。。");
    }
}
